<?php

namespace App\Http\Middleware;

use App\Models\Link;
use App\Models\Project;
use Illuminate\Support\Facades\Session;
use Closure;

class AuthHome
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(!session('user')){
            return redirect('/');
        }
        $user_id    = Session::get('user')->id;
        $search     = '';
        if( isset($_GET['project_name']) && !empty($_GET['project_name'])){
            $search           = $request->get('project_name');
        }
        if( !empty($search) ){
            $list   = Project::where(function ($query) use ($search) {
                $query->where('project_name', 'LIKE', '%' . $search. '%')
                    ->orwhere('project_pinyin', 'LIKE', '%,'.$search.',%');
            })->where('user_id', 'LIKE', '%,'.$user_id.',%')->paginate(15);
        }else{
            $list   = Project::where('user_id', 'LIKE', '%,'.$user_id.',%')->paginate(15);
        }
        $Link       = Link::get();
        view()->share('project',$list);
        view()->share('link',$Link);
        //view()->with(array('project'=>$list, 'link'=>$Link));
        return $next($request);
    }
}
